<template>
  <div id="map" style="width: 100%; height: 100%;">
  </div>
</template>
<script setup>
import styleJson from "/src/assets/custom_map_config.json"
import {onMounted, watch} from "vue";
import request from "@/utils/request.js";
import PointClickDialog from "@/views/homeComponents/mapComponent/PointClickDialog.vue";
import store from "@/store/index.js";
let map = null;
let custView = null;
let point = new BMapGL.Point(112.4913267744316, 39.35989256841454); // 设置中心点坐标
let items = [{name: "111"}]
onMounted(() => {
  initBaiduMap()
})

watch(()=>store.state.currentClientInfo,(newVal, oldVal)=>{
  if (store.state.currentClientInfo.latitude!==undefined){
    if (store.state.currentClientInfo.latitude!==null){
      map.centerAndZoom(new BMapGL.Point(store.state.currentClientInfo.longitude, store.state.currentClientInfo.latitude), 15); // 设置中心点坐标和地图级
      let pointData = []
      pointData.push({
        geometry: {
          type: 'Point',
          coordinates: [store.state.currentClientInfo.longitude,store.state.currentClientInfo.latitude],
        },
      })
      addMarker(pointData)
    }
  }else {
    if (custView!==null){
      custView.removeAllLayers()
      map.centerAndZoom(point, 8); // 设置中心点坐标和地图级
    }
  }
})

// 初始化百度地图
const initBaiduMap = () => {
  /** 初始化地图Start */
  map = new BMapGL.Map("map",{minZoom:6,maxZoom: 14}); // 创建地图实例

  map.centerAndZoom(point, 8); // 地图初始化，同时设置地图展示级别
  map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
  /** 初始化地图End */
  map.setMapStyleV2({
    styleJson: styleJson
  });
  getEquipmentPoint()
  custView = new mapvgl.View({
    map: map
  });
};

const addMarker=(pointData)=>{
  custView.removeAllLayers()
  var layer = new mapvgl.IconLayer({
    width: 60,
    height: 80,
    offset: [0, - 80 / 2],
    icon: '/icons8_red.png',
    data: pointData,
  });
  custView.addLayer(layer);
}

const getPoint = (pointData) => {
  var view = new mapvgl.View({
    map: map
  });
  var layer = new mapvgl.ClusterLayer({
    minSize: 50,
    maxSize: 60,
    // iconOptions: {
    //   icon: '/icons8_green.png',
    // },
    clusterRadius: 50,
    showText: true,
    maxZoom: 19,
    minZoom: 4,
    gradient: {
      0.0: 'rgb(50, 50, 256)',
      0.1: 'rgb(50, 250, 56)',
      0.5: 'rgb(250, 250, 56)',
      1.0: 'rgb(250, 50, 56)'
    },
    textOptions: {
      fontSize: 12,
      color: 'black',
      format: function (count) {
        return count;
      }
    },
    enablePicked: true,
    onClick(e) {
      if (e.dataItem) {
        // 可通过dataItem下面的children属性拿到被聚合的所有点
        let info=[];
        if (e.dataItem.children === undefined) {
          info.push(e.dataItem.geometry)
        } else {
          e.dataItem.children.forEach(item => {
            info.push(item.geometry)
          })
        }
        store.commit("setPointClickDialogData",info)
        let pointData = []
        pointData.push({
          geometry: {
            type: 'Point',
            coordinates: [e.dataItem.geometry.coordinates[0],e.dataItem.geometry.coordinates[1]],
          },
        })
        addMarker(pointData)
        map.centerAndZoom(new BMapGL.Point(e.dataItem.geometry.coordinates[0],e.dataItem.geometry.coordinates[1]), 15); // 初始化地图,设置中心点坐标和地图级
        store.state.pointClickDialog=true
      }
    },
    // onMousemove(e) {
    //   if (e.dataItem) {
    //     let sContent = ""
    //     if (e.dataItem.children === undefined) {
    //       sContent = "<div style='height: 200px;width: 200px;overflow-y: auto;'>";
    //       let url = e.dataItem.geometry.pageTurnUrl
    //       sContent += `<div onclick="window.open('${url}')" style="padding: 5px;font-size: 20px; transition: background-color 0.3s ease;cursor: pointer" onmouseover="this.style.backgroundColor='#f0f0f0';" onmouseout="this.style.backgroundColor='';">` + e.dataItem.geometry.name + '</div>';
    //       sContent += "</div>"
    //     } else {
    //       sContent = "<div style='height: 200px;width: 200px;overflow-y: auto;'>";
    //       // for (var i=0;i<20;i++){
    //       //   let url=e.dataItem.children[1].geometry.pageTurnUrl
    //       //   sContent += `<div onclick="window.open('${url}')" style="padding: 5px;font-size: 20px; transition: background-color 0.3s ease;cursor: pointer" onmouseover="this.style.backgroundColor='#f0f0f0';" onmouseout="this.style.backgroundColor='';">`+e.dataItem.children[1].geometry.name+'</div>';
    //       // }
    //       for (var i = 0; i < e.dataItem.children.length; i++) {
    //         let url = e.dataItem.children[i].geometry.pageTurnUrl
    //         sContent += `<div onclick="window.open('${url}')" style="padding: 5px;font-size: 20px; transition: background-color 0.3s ease;cursor: pointer" onmouseover="this.style.backgroundColor='#f0f0f0';" onmouseout="this.style.backgroundColor='';">` + e.dataItem.children[i].geometry.name + '</div>';
    //       }
    //       sContent += "</div>"
    //     }
    //     var infoWindow = new BMapGL.InfoWindow(sContent);  // 创建信息窗口对象
    //     infoWindow.setWidth(220)
    //     infoWindow.setHeight(210)
    //     // 获取点击点的坐标
    //     var lng = e.dataItem.geometry.coordinates[0];
    //     var lat = e.dataItem.geometry.coordinates[1];
    //     map.openInfoWindow(infoWindow, new BMapGL.Point(lng, lat));
    //   }
    // },
    data: pointData
  });
  view.addLayer(layer);
}
const getEquipmentPoint = () => {
  let level = parseInt(JSON.parse(localStorage.getItem("user")).level)
  let selectedOrganizationId = JSON.parse(localStorage.getItem("user")).organization
  let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
  let clientIds;
  if (isAllClient === "1") {
    clientIds = JSON.parse(localStorage.getItem("user")).clientIds;
  } else {
    clientIds = [];
  }
  request.get("/client/findMapByClient?organizationId="+selectedOrganizationId+"&level="+level+"&isAllClient="+isAllClient+"&clientIds="+clientIds).then(res=>{
    let pointData = []
    for (var i = 0; i < res.data.length; i++) {
      pointData.push({
        geometry: {
          type: 'Point',
          name: res.data[i].equipmentName,
          pageTurnUrl: res.data[i].pageTurnUrl,
          coordinates: [res.data[i].longitude, res.data[i].latitude],
          clientCount:res.data[i].clientCount,
          equipmentCount:res.data[i].equipmentCount,
          nowWarnCount:res.data[i].nowWarnCount,
          clientName:res.data[i].clientName,
        },
      })
    }
    getPoint(pointData)
  })
}
</script>

<style scoped>

</style>
